/**
 * 
 */
package com.xbang.attendance.security.support;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.security.context.SecurityContextHolder;

import com.xbang.attendance.entity.role.Resource;
import com.xbang.attendance.entity.role.Role;
import com.xbang.attendance.entity.role.User;

/**
 * @author dev.zhang
 * @author Downpour
 * 
 */
public class SecurityUserHolder {

	/**
	 * Returns the current user
	 * 
	 * @return
	 */
	public static User getCurrentUser() {
		return (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
	}

	/**
	 * Returns the current role menus
	 * 
	 * @return
	 */
	public static List<Resource> getCurrentMenuResources() {
		User currentUser = getCurrentUser();

		Map<String, Role> roles = currentUser.getRoles();

		List<Resource> resources = new ArrayList<Resource>();

		Set<Resource> tmpResources = new HashSet<Resource>();
		for (Iterator<Map.Entry<String, Role>> roleEntrys = roles.entrySet().iterator(); roleEntrys.hasNext();) {
			Map.Entry<String, Role> roleEntry = roleEntrys.next();
			Role role = roleEntry.getValue();
			if (role.getName().endsWith("_MENU")) {
				tmpResources.addAll(role.getResources());
			}
		}

		resources.addAll(tmpResources);
//		Role menuRole = currentUser.getRoles().get(currentUser.getPosition() + "_MENU");
		return resources;
	}

	/**
	 * Returns the current role submenus
	 * 
	 * @return
	 */
	public static List<Resource> getCurrentSubmenuResources() {
		User currentUser = getCurrentUser();
		
		Map<String, Role> roles = currentUser.getRoles();

		List<Resource> resources = new ArrayList<Resource>();

		Set<Resource> tmpResources = new HashSet<Resource>();
		for (Iterator<Map.Entry<String, Role>> roleEntrys = roles.entrySet().iterator(); roleEntrys.hasNext();) {
			Map.Entry<String, Role> roleEntry = roleEntrys.next();
			Role role = roleEntry.getValue();
			if (role.getName().endsWith("_SUBMENU")) {
				tmpResources.addAll(role.getResources());
			}
		}

		resources.addAll(tmpResources);
		
		
//		Role menuRole = currentUser.getRoles().get(currentUser.getPosition() + "_SUBMENU");
		return resources;
	}

}
